#请求模型

from pydantic import BaseModel, ValidationError
from typing import Optional, List,Annotated
from datetime import datetime

class User(BaseModel):
    id:int                              #必填
    name: str = "John snow"             #有默认值的可选参数
    sign_date :Optional[datetime]=None  #默认值为null的可选参数
    friends: List[int]                  #储存整数类型的列表，或者可以转换成整数的元素[1,2],[1,2,"3"]
#两个东西怎么产生关系
john ={
    "id" :1001,
    "name":"Mark",
    "sign_date":datetime.now(),
    "friends":[1,2,"3"]
}
u1 = User(**john)
"""

print(u1.name)
print(u1.friends)
print(str(u1.sign_date))
print(repr(u1.sign_date))
print(u1.dict)
"""
try:
    #还有校验功能
    u2 = User(
        id = 1002,
        name = "Jack",
        friends = [1,2,3]
    )
    print(u2.friends)
except ValidationError as e:
    print(e.json())


print('json',u1.json)

#可以通过User的昂发来实例化验证
u3 = User.model_validate(john)
"""
u3 = User.model_validate_json()
u3 = User.model_validate_strings()
"""
print('u3',u3.dict)

print(User.model_validate_json('{"id":101,"name":"大力","sign_date":"2024-12-09 12:20","friends":[1,2,"3"]}'))
print("-" *30)
# 这就没验证了 User_data = {"id":"abc","name":"大力","sign_date":"2024-12-09 12:20","friends":[1,2,"3"]}
print('所有字段:',User.model_fields.keys())

class Sound(BaseModel):
    sound:str

class Dog(BaseModel):
    name:str
    weight: float =2.0
    # Dog模型中的sound类型是另外一个模型Sound
    sound :List[Sound]

dh = Dog(
    name ="大黄",
    weight = 3.5,
    sound = [{"sound":"汪汪"},{"sound":"嘤嘤"}]
)

print(dh.dict)

def validate_num(n:int) ->bool:
    return n>0

def process_num(num:Annotated[int,validate_num]):
    if validate_num(num):
        print(num)
    else:
        print("非法的参数")

